package com.example.demo.ms;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;

/**
 *  让三个线程 同时执行
 */
public class TestThreadCountDownLatch {


    public static void main(String[] args) {

        subThreadUsingCompletableFuture();


    }

    /**
     * 三个线程同时执行
     */
    public static void tongshi(){
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    countDownLatch.await();
                    System.out.println(System.currentTimeMillis());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();

        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        countDownLatch.countDown();
    }

    /**
     *  等待所有的子线程执行结束之后在来执行后续任务
     */
    public static void subThread(){
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            final int index = i;
            new Thread(() -> {
                try {
                    Thread.sleep(1000 + ThreadLocalRandom.current().nextInt(1000));
                    System.out.println("finish" + index + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    countDownLatch.countDown();
                }
            }).start();

        }
        try {
            countDownLatch.await();
            System.out.println("执行后续任务---");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * CompletableFuture 改写
     */
    public static void subThreadUsingCompletableFuture() {
        // 创建一个数组保存三个异步任务
        CompletableFuture<Void>[] futures = new CompletableFuture[3];

        for (int i = 0; i < 3; i++) {
            final int index = i;
            // 启动异步任务并保存到数组中
            futures[i] = CompletableFuture.runAsync(() -> {
                try {
                    Thread.sleep(1000 + ThreadLocalRandom.current().nextInt(1000));
                    System.out.println("finish" + index + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }

        // 使用 allOf 等待所有任务完成
        CompletableFuture.allOf(futures).thenRun(() -> {
            System.out.println("执行后续任务---");
        }).join(); // 阻塞主线程直到所有任务完成
    }
}
